<?php
namespace addons\weixin\library;

use EasyWeChat\Factory;
use think\Response;

class WechatService
{
    private static $instance = null;

    public static function options()
    {
        $wechat_data = \app\admin\model\weixin\Config::where(['group' => 'weixin'])->select();
        foreach ($wechat_data as $k => $v) {
            $value = $v->toArray();
            if (in_array($value['type'], ['selects', 'checkbox', 'images', 'files'])) {
                $value['value'] = explode(',', $value['value']);
            }
            if ($value['type'] == 'array') {
                $value['value'] = (array)json_decode($value['value'], true);
            }
            $wechat[$value['name']] = $value['value'];
        }

        $config = [
            'app_id' => isset($wechat['appid']) ? trim($wechat['appid']) : '',
            'secret' => isset($wechat['appsecret']) ? trim($wechat['appsecret']) : '',
            'token' => isset($wechat['token']) ? trim($wechat['token']) : '',
            'oauth' => [
                'scopes' => ['snsapi_userinfo']
            ]
        ];
        if ((int)$wechat['encode'] > 0 && !empty($wechat['encodingaeskey'])) {
            $config['aes_key'] = $wechat['encodingaeskey'];
        }
        return $config;
    }

    public static function application($cache = false)
    {
        (self::$instance === null || $cache === true) && (self::$instance = Factory::officialAccount(self::options()));
        return self::$instance;
    }

    public static function serve(): Response
    {
        $wechat = self::application(true);
        $server = $wechat->server;
        Event::hook($server);
        $response = $server->serve();
        return response($response->getContent());
    }

    /**
     * 微信公众号菜单接口
     * @return object
     */
    public static function menuService()
    {
        return self::application()->menu;
    }


    /**
     * 用户标签接口
     * @return object
     */
    public static function userTagService()
    {
        return self::application()->user_tag;
    }

    /**
     * 用户授权
     * @return object
     */
    public static function oauthService()
    {
        return self::application()->oauth;
    }

    /**
     * 用户接口
     * @return object
     */
    public static function userService()
    {
        return self::application()->user;
    }

    /**
     * 获得用户信息
     * @param array|string $openid
     * @return object
     */
    public static function getUserInfo($openid)
    {
        $userService = self::userService();
        $userInfo = $userService->get($openid);
        return $userInfo;
    }

    /**
     * 获得用户openid列表
     * @param array|string $openid
     * @return object
     */
    public static function getUserList($next_openid = null)
    {
        $userService = self::userService();
        $userList = $userService->list($next_openid);
        return $userList;
    }

    /**
     * @notes 获得用户列表信息
     * @author 兴
     * @date 2022/10/31 22:57
     */
    public static function getUserListInfo($list = [])
    {
        $userService = self::userService();
        if (empty($list)) {
            $list = self::getUserList();
        } else {
            $list['data']['openid'] = $list;
        }
        if (!isset($list['data']['openid'])) {
            return [];
        }
        $userList = $userService->select($list['data']['openid']);
        return $userList;
    }

    /**
     * @notes 模板消息接口
     * @author 兴
     * @date 2022/10/31 22:57
     */
    public static function noticeService()
    {
        return self::application()->template_message;
    }

    /**
     * @notes 发送模板消息
     * @author 兴
     * @date 2022/10/31 21:17
     */
    public static function sendTemplate($openid, $templateId, array $data, $url = null, $defaultColor = null)
    {
        $data = [
            'touser' => $openid,
            'template_id' => $templateId,
            'url' => $url,
            'data' => $data
        ];
        return self::noticeService()->send($data);
    }

    /**
     * @notes jsSdk
     * @author 兴
     * @date 2022/10/31 22:48
     */
    public static function jsSdk($url = '')
    {
        $apiList = [
            'editAddress', 'openAddress', 'updateTimelineShareData', 'updateAppMessageShareData', 'onMenuShareTimeline',
            'onMenuShareAppMessage', 'onMenuShareQQ', 'onMenuShareWeibo', 'onMenuShareQZone', 'startRecord',
            'stopRecord', 'onVoiceRecordEnd', 'playVoice', 'pauseVoice', 'stopVoice', 'onVoicePlayEnd', 'uploadVoice',
            'downloadVoice', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage', 'translateVoice',
            'getNetworkType', 'openLocation', 'getLocation', 'hideOptionMenu', 'showOptionMenu', 'hideMenuItems',
            'showMenuItems', 'hideAllNonBaseMenuItem', 'showAllNonBaseMenuItem', 'closeWindow', 'scanQRCode',
            'chooseWXPay', 'openProductSpecificView', 'addCard', 'chooseCard', 'openCard'
        ];
        $jsService = self::application()->jssdk;
        if ($url) {
            $jsService->setUrl($url);
        }
        return $jsService->buildConfig($apiList, $debug = false, $beta = false, $json = false);
    }

}
